import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Notification, NotificationFilter } from '@/types/notification'

export const useNotificationStore = defineStore('notification', () => {
  // 状态
  const notifications = ref<Notification[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const unreadCount = computed(() => 
    notifications.value.filter(n => !n.read).length
  )

  const hasUnread = computed(() => unreadCount.value > 0)

  // 方法
  const addNotification = (notification: Omit<Notification, 'id' | 'createdAt' | 'read'>) => {
    const newNotification: Notification = {
      id: Date.now().toString(),
      createdAt: new Date(),
      read: false,
      ...notification
    }
    
    notifications.value.unshift(newNotification)
    
    // 显示桌面通知
    if (notification.type === 'task' || notification.type === 'system') {
      showDesktopNotification(newNotification)
    }
    
    // 限制通知数量
    if (notifications.value.length > 100) {
      notifications.value = notifications.value.slice(0, 100)
    }
  }

  const markAsRead = (id: string) => {
    const notification = notifications.value.find(n => n.id === id)
    if (notification) {
      notification.read = true
    }
  }

  const markAllAsRead = () => {
    notifications.value.forEach(n => {
      n.read = true
    })
  }

  const deleteNotification = (id: string) => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      notifications.value.splice(index, 1)
    }
  }

  const clearAll = () => {
    notifications.value = []
  }

  const getFilteredNotifications = (filter: NotificationFilter) => {
    return notifications.value.filter(notification => {
      switch (filter) {
        case 'unread':
          return !notification.read
        case 'task':
          return notification.type === 'task'
        case 'system':
          return notification.type === 'system'
        case 'all':
        default:
          return true
      }
    })
  }

  const showDesktopNotification = (notification: Notification) => {
    if ('Notification' in window && Notification.permission === 'granted') {
      const desktopNotification = new Notification(notification.title, {
        body: notification.message,
        icon: '/favicon.ico',
        tag: notification.id
      })

      desktopNotification.onclick = () => {
        window.focus()
        markAsRead(notification.id)
        desktopNotification.close()
      }

      // 自动关闭
      setTimeout(() => {
        desktopNotification.close()
      }, 5000)
    }
  }

  // 任务相关通知
  const notifyTaskStarted = (taskId: string, filename: string) => {
    addNotification({
      type: 'task',
      title: '转换开始',
      message: `文件 "${filename}" 开始转换`,
      taskId
    })
  }

  const notifyTaskCompleted = (taskId: string, filename: string, outputFormat: string) => {
    addNotification({
      type: 'task',
      title: '转换完成',
      message: `文件 "${filename}" 已成功转换为 ${outputFormat.toUpperCase()}`,
      taskId,
      actions: [
        { label: '下载', action: 'download' },
        { label: '查看', action: 'view' }
      ]
    })
  }

  const notifyTaskFailed = (taskId: string, filename: string, error: string) => {
    addNotification({
      type: 'task',
      title: '转换失败',
      message: `文件 "${filename}" 转换失败：${error}`,
      taskId,
      actions: [
        { label: '重试', action: 'retry' },
        { label: '查看详情', action: 'details' }
      ]
    })
  }

  // 系统通知
  const notifySystemUpdate = (version: string) => {
    addNotification({
      type: 'system',
      title: '系统更新',
      message: `新版本 ${version} 可用，建议更新以获得更好的体验`,
      actions: [
        { label: '立即更新', action: 'update' },
        { label: '稍后提醒', action: 'later' }
      ]
    })
  }

  const notifyStorageWarning = (usedPercent: number) => {
    addNotification({
      type: 'system',
      title: '存储空间警告',
      message: `存储空间已使用 ${usedPercent}%，建议清理旧文件`,
      actions: [
        { label: '清理文件', action: 'cleanup' },
        { label: '查看详情', action: 'storage' }
      ]
    })
  }

  const notifyMaintenanceMode = (startTime: Date, duration: number) => {
    addNotification({
      type: 'system',
      title: '系统维护通知',
      message: `系统将于 ${startTime.toLocaleString()} 进行维护，预计持续 ${duration} 小时`,
      actions: [
        { label: '了解详情', action: 'maintenance' }
      ]
    })
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 初始化
  const init = () => {
    // 从本地存储加载通知
    try {
      const saved = localStorage.getItem('notifications')
      if (saved) {
        const parsed = JSON.parse(saved)
        notifications.value = parsed.map((n: any) => ({
          ...n,
          createdAt: new Date(n.createdAt)
        }))
      }
    } catch (err) {
      console.error('Failed to load notifications:', err)
    }
  }

  // 保存到本地存储
  const saveToStorage = () => {
    try {
      localStorage.setItem('notifications', JSON.stringify(notifications.value))
    } catch (err) {
      console.error('Failed to save notifications:', err)
    }
  }

  // 监听通知变化并保存
  const unwatchNotifications = ref<(() => void) | null>(null)
  
  const startWatching = () => {
    if (unwatchNotifications.value) return
    
    unwatchNotifications.value = () => {
      saveToStorage()
    }
  }

  const stopWatching = () => {
    if (unwatchNotifications.value) {
      unwatchNotifications.value()
      unwatchNotifications.value = null
    }
  }

  return {
    // 状态
    notifications,
    loading,
    error,
    
    // 计算属性
    unreadCount,
    hasUnread,
    
    // 方法
    addNotification,
    markAsRead,
    markAllAsRead,
    deleteNotification,
    clearAll,
    getFilteredNotifications,
    
    // 任务通知
    notifyTaskStarted,
    notifyTaskCompleted,
    notifyTaskFailed,
    
    // 系统通知
    notifySystemUpdate,
    notifyStorageWarning,
    notifyMaintenanceMode,
    
    // 工具方法
    clearError,
    init,
    startWatching,
    stopWatching
  }
})